package com.service.business.merchant.controller;

import com.service.business.base.dto.LoginUserSession;
import com.service.business.framework.log.RequestLog;
import com.service.business.merchant.controller.rep.MerchantPageRep;
import com.service.business.merchant.controller.rep.MerchantRep;
import com.service.business.merchant.controller.rep.MerchantSelfRep;
import com.service.business.merchant.controller.req.MerchantEnterReq;
import com.service.business.merchant.controller.req.MerchantPageReq;
import com.service.business.merchant.controller.req.MerchantUpdateReq;
import com.service.business.merchant.service.MerchantService;
import com.service.business.support.MemberMerchantLockUtils;
import com.service.business.support.SessionUtil;
import com.service.core.rest.BaseController;
import com.service.core.rest.response.BaseResponse;
import com.service.core.rest.response.OneResponse;
import com.service.core.rest.response.PageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * 商家信息表
 *
 * @author xxxx
 * @email xxxx@qq.com
 * @date 2020-03-28 12:54:56
 */
@RestController
@RequestMapping("merchant")
public class MerchantController extends BaseController {
    @Autowired
    private SessionUtil sessionUtil;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private MemberMerchantLockUtils memberMerchantLockUtils;

    @PostMapping("page")
    @RequestLog("商家分页列表")
    public PageResponse<MerchantPageRep> page(@RequestBody MerchantPageReq pageReq) {
        return successQueryPageResponse(merchantService.page(pageReq));
    }

    @RequestLog("申请入驻")
    @PostMapping("apply-enter")
    public BaseResponse enter(@RequestBody @Validated MerchantEnterReq enterReq) {
        LoginUserSession session = sessionUtil.getUser();
        try {
            if (memberMerchantLockUtils.lockCreateMerchant(session.getUserId())) {
                merchantService.applyEnter(enterReq);
            }
        } finally {
            memberMerchantLockUtils.unlockCreateMerchant(session.getUserId());
        }
        return successBaseResponse();
    }

    @RequestLog("商家详情-商家编码")
    @GetMapping("detail")
    public OneResponse<MerchantSelfRep> detail() {
        return successQueryOneResponse(merchantService.detail());
    }

    @RequestLog("商家详情-更新")
    @PostMapping("update")
    public BaseResponse update(@RequestBody MerchantUpdateReq updateReq) {
        merchantService.update(updateReq);
        return successBaseResponse();
    }

    @RequestLog("商家详情-商家编码")
    @GetMapping("detail/{merchantNo}")
    public OneResponse<MerchantRep> detail(@PathVariable("merchantNo") String merchantNo) {
        return successQueryOneResponse(merchantService.detail(merchantNo));
    }


}
